<?php

namespace App\Http\Middleware\Admin\V1;

use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Exceptions\Admin\V1\GeneralException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class LoginAuthMiddleware
{
    /**
     * @var JWTAuth
     */
    protected $auth;

    /**
     * LoginAuthMiddleware constructor.
     * @param JWTAuth $auth
     */
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws GeneralException
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/25/11:13
     */
    public function handle(Request $request, Closure $next)
    {
        $this->checkToken($request);

        try {
            if (!$this->auth->parseToken()->authenticate()) {
                throw new GeneralException(GeneralException::ADMIN_LOGIN_RETRIEVE_INVALID);
            }
        }
        catch ( TokenExpiredException $exception ) {
            throw new GeneralException(GeneralException::ADMIN_LOGIN_RETRIEVE_INVALID);
        }
        catch ( JWTException $exception ) {
            throw new GeneralException(GeneralException::ADMIN_LOGIN_RETRIEVE_INVALID);
        }

        return $next($request);
    }

    /**
     * @param Request $request
     * @throws GeneralException
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/3/25/10:50
     */
    public function checkToken(Request $request)
    {
        if (!$this->auth->parser()->setRequest($request)->hasToken()) {
            throw new GeneralException(GeneralException::ADMIN_LOGIN_RETRIEVE_INVALID);
        }
    }
}
